package com.foodcommunity.controller;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.DataAnalysisDTO;
import com.foodcommunity.dto.FoodPostDTO;
import com.foodcommunity.entity.*;
import com.foodcommunity.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    
    @Autowired
    private FoodPostService foodPostService;
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private RestaurantService restaurantService;

    @Autowired
    private DataAnalysisService dataAnalysisService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;


    private static final int PAGE_SIZE = 10;  // 定义每页显示数量

    @GetMapping("/")
    public String index(Model model) {
        // 获取热门美食日记
        model.addAttribute("hotPosts", foodPostService.getHotPosts());
        // 获取美食分类（包含文章数量）
        model.addAttribute("categories", categoryService.getCategoriesWithPostCount());
        // 获取热门餐厅
        model.addAttribute("hotRestaurants", restaurantService.getHotRestaurants());
        // 获取更多美食日记（第一页）
        model.addAttribute("morePosts", foodPostService.getMorePosts(1, PAGE_SIZE));
        return "index";
    }

    @GetMapping("/posts/more")
    @ResponseBody
    public Object loadMorePosts(@RequestParam(defaultValue = "1") int page) {
        return foodPostService.getMorePosts(page, PAGE_SIZE);
    }



    /**
     * 美食分类页
     */
    @GetMapping("/category")
    public String category(Model model) {
        // 获取所有分类及其文章数量
        List<Map<String, Object>> categories = categoryService.getCategoriesWithPostCount();
        model.addAttribute("categories", categories);
        return "category/list";
    }

    /**
     * 美食日记列表页
     */
    @GetMapping("/posts")
    public String posts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false, defaultValue = "latest") String sort,
            Model model) {

        // 获取美食日记列表，根据筛选条件
        List<FoodPostDTO> posts;
        if (category != null && !category.isEmpty()) {
            // 根据分类筛选
            posts = foodPostService.getPostsByCategory(category, page, size, sort);
        } else {
            // 获取所有文章，根据排序方式
            posts = foodPostService.getPostsBySort(sort, page, size);
        }
        
        model.addAttribute("posts", posts);
        model.addAttribute("currentPage", page);
        
        // 获取总文章数和计算总页数
        int totalPosts = foodPostService.getTotalPostsCount(category);
        int totalPages = (int) Math.ceil((double) totalPosts / size);
        model.addAttribute("totalPages", totalPages > 0 ? totalPages : 1);
        
        // 获取所有分类及其文章数量
        List<Map<String, Object>> categories = categoryService.getCategoriesWithPostCount();
        model.addAttribute("categories", categories);
        
        // 保存筛选条件，用于分页和显示当前选中状态
        model.addAttribute("category", category);
        model.addAttribute("sort", sort);

        return "post/list";
    }
    /**
     * 美食日记详情页
     */
        @GetMapping("/post/{id}")
    public String postDetail(@PathVariable Long id, Model model) {
        // 获取帖子详情
        Result<FoodPost> result = foodPostService.getPostDetail(id);
        if (result!=null) {
            FoodPost post = result.getData();

            // 获取作者信息
            User author = userService.getUserInfo(post.getUserId()).getData();
            if (author != null) {
                model.addAttribute("authorName", author.getNickname() != null ? author.getNickname() : author.getUsername());
                model.addAttribute("authorAvatar", author.getAvatar());
            }

            // 处理第一张图片
            if (post.getImages() != null && !post.getImages().isEmpty()) {
                String firstImage = post.getImages().split(",")[0];
                model.addAttribute("firstImage", firstImage);
            }

            // 获取分类名称
            if (post.getCategoryId() != null) {
                Category category = categoryService.getCategoryById(post.getCategoryId());
                if (category != null) {
                    model.addAttribute("categoryName", category.getName());
                }
            }

            model.addAttribute("post", post);

            // 增加浏览量
            foodPostService.incrementViews(id);

            // 获取评论列表
            List<Comment> comments = commentService.getPostComments(id);
            model.addAttribute("comments", comments);
            model.addAttribute("commentCount", comments.size());

            // 获取相关文章
            List<FoodPostDTO> relatedPosts = foodPostService.getRelatedPosts(id, 3);
            model.addAttribute("relatedPosts", relatedPosts);
        }

        return "post/detail";
    }


    /**
     * 餐厅列表页
     */
    @GetMapping("/restaurant")
    public String restaurantList(
            @RequestParam(required = false) String cuisineType,
            @RequestParam(required = false) Integer minPrice,
            @RequestParam(required = false) Integer maxPrice,
            @RequestParam(required = false) Double minRating,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size,
            Model model) {

        Map<String, Object> result = restaurantService.getRestaurantsByCondition(
                cuisineType, minPrice, maxPrice, minRating, page, size);

        model.addAttribute("restaurants", result.get("restaurants"));
        model.addAttribute("totalPages", result.get("totalPages"));
        model.addAttribute("currentPage", page);

        return "restaurant/list";
    }

    /**
     * 餐厅详情页
     */
    @GetMapping("/restaurant/{id}")
    public String restaurantDetail(
            @PathVariable Long id,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model,
            HttpSession session) {

        // 获取餐厅详情
        Restaurant restaurant = restaurantService.getRestaurantDetail(id).getData();
        model.addAttribute("restaurant", restaurant);

        // 获取餐厅评论
        Map<String, Object> reviewsResult = restaurantService.getRestaurantReviewsWithPage(id, page, size);
        model.addAttribute("reviews", reviewsResult.get("reviews"));
        model.addAttribute("totalPages", reviewsResult.get("totalPages"));
        model.addAttribute("currentPage", page);

        // 获取推荐餐厅
        User user = (User) session.getAttribute("user");
        List<Map<String, Object>> recommendations;
        if (user != null) {
            // 根据用户偏好推荐
            recommendations = dataAnalysisService.getRecommendedRestaurants(user.getId(), 5);
        } else {
            // 获取热门餐厅
            recommendations = dataAnalysisService.getHotRestaurantRanking(5);
        }
        model.addAttribute("recommendations", recommendations);

        return "restaurant/detail";
    }

    /**
     * 餐厅地图页
     */
    @GetMapping("/restaurant/map")
    public String restaurantMap() {
        return "restaurant/map";
    }

    /**
     * 数据分析页
     */
    @GetMapping("/analysis")
    public String analysis(Model model, HttpSession session) {
        // 获取当前用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 检查用户角色，只有admin才能访问
        if (!"admin".equals(user.getRole())) {
            return "redirect:/";
        }
        
        // 获取总体数据分析
        DataAnalysisDTO analysis = dataAnalysisService.getOverallAnalysis();
        model.addAttribute("analysis", analysis);

        // 获取热门餐厅排行榜
        List<Map<String, Object>> hotRestaurants = dataAnalysisService.getHotRestaurantRanking(10);
        model.addAttribute("hotRestaurants", hotRestaurants);

        // 获取热门美食日记排行榜
        List<Map<String, Object>> hotPosts = dataAnalysisService.getHotFoodRanking(10);
        model.addAttribute("hotPosts", hotPosts);

        // 获取统计数据
        // 餐厅总数
        int totalRestaurants = 0;
        try {
            Map<String, Object> restaurantResult = restaurantService.getRestaurantsByCondition(null, null, null, null, 1, 1);
            if (restaurantResult.containsKey("total")) {
                totalRestaurants = ((Number) restaurantResult.get("total")).intValue();
            }
        } catch (Exception e) {
            totalRestaurants = 0;
        }

        // 帖子总数 - 由于没有getPostsWithPage方法，我们尝试从其他地方获取
        int totalPosts = 0;
        try {
            // 尝试从数据分析服务获取帖子总数
            if (analysis != null && analysis.getCategoryStats() != null && !analysis.getCategoryStats().isEmpty()) {
                // 计算所有分类的帖子总数
                totalPosts = analysis.getCategoryStats().stream()
                        .mapToInt(map -> ((Number) map.getOrDefault("post_count", 0)).intValue())
                        .sum();
            }
        } catch (Exception e) {
            totalPosts = 0;
        }

        // 评论总数
        int totalReviews = 0;
        try {
            // 尝试从数据分析获取评论总数
            if (analysis != null && analysis.getMonthlyTrends() != null && !analysis.getMonthlyTrends().isEmpty()) {
                // 计算所有月份的评论总数
                totalReviews = analysis.getMonthlyTrends().stream()
                        .mapToInt(map -> ((Number) map.getOrDefault("comment_count", 0)).intValue())
                        .sum();
            }
        } catch (Exception e) {
            totalReviews = 0;
        }

        // 用户总数
        int totalUsers = 0;
        try {
            // 尝试从数据分析获取用户总数
            if (analysis != null && analysis.getUserActivityStats() != null) {
                totalUsers = analysis.getUserActivityStats().size();
            }
        } catch (Exception e) {
            totalUsers = 0;
        }

        model.addAttribute("totalRestaurants", totalRestaurants);
        model.addAttribute("totalPosts", totalPosts);
        model.addAttribute("totalReviews", totalReviews);
        model.addAttribute("totalUsers", totalUsers);

        // 获取用户个性化推荐（已经有user变量，不需要重复获取）
        if (user != null) {
            // 获取用户偏好
            Map<String, Object> userPreferences = dataAnalysisService.getUserPreferences(user.getId());
            model.addAttribute("userPreferences", userPreferences);

            // 获取推荐餐厅
            List<Map<String, Object>> recommendedRestaurants = dataAnalysisService.getRecommendedRestaurants(user.getId(), 3);
            model.addAttribute("recommendedRestaurants", recommendedRestaurants);

            // 获取推荐美食日记
            List<Map<String, Object>> recommendedPosts = dataAnalysisService.getRecommendedPosts(user.getId(), 3);
            model.addAttribute("recommendedPosts", recommendedPosts);
        }

        return "analysis/dashboard";
    }
}